from django_redis import get_redis_connection
from redis import RedisError
from rest_framework import serializers



import logging
logger = logging.getLogger('django')


class SMSCodeSerializer(serializers.Serializer):
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4,min_length=4)


    def validate(self,attrs):
        image_code_id = attrs.get('image_code_id')
        text = attrs.get('text')
        redis = get_redis_connection('verify')
        real_text = redis.get('img_%s' %image_code_id)
        real_text = real_text.decode()
        # print(real_text)

        try:
            redis.delete('img_%s'%image_code_id)
        except RedisError as e:
            logger.error(e)

        if real_text.lower() != text.lower():
            raise serializers.ValidationError('图片验证码无效')



        mobile = self.context['view'].kwargs['mobile']


        send_flag = redis.get('send_flag_%s'%mobile)
        if send_flag:
            raise serializers.ValidationError('短信过如频繁')


        return attrs